import random
import time

from sqlalchemy import and_

from exts import db
from flask import Blueprint, request, Response, jsonify, render_template, url_for, redirect, session
import json

from data.model import Data

data = Blueprint('data', __name__);

# 信息列表
@data.route('data_list', methods=['GET', 'POST'])
def data_list():
    data_list = Data.query.all()
    return render_template('data_list.html', data_list=data_list)

# 记录者 搜索
@data.route('/data/search', methods=['GET', 'POST'])
def search():
    keyword = request.args.get('keyword')
    data_list = Data.query.filter(
        Data.name.like('%{keyword}%'.format(keyword=keyword))
    ).all()
    return render_template('data_list.html', data_list=data_list)

# 删除信息
@data.route('/data/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    data = Data.query.filter(
        Data.id == id
    ).first()
    db.session.delete(data)
    db.session.commit()
    return redirect(url_for('data.data_list'))

# 信息详情，编辑，更新，添加 
@data.route('/data/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        data = Data.query.filter(
            Data.id == id
        ).first()
        if option == 'detail':
            return render_template('data_editor.html', data=data)
        else:
            return render_template('data_editor.html', data=data, update=True)
    else:
        id = request.form.get('id')
        beizhu = request.form.get('beizhu')
        name = request.form.get('name')
        content = request.form.get('content')

        data = Data.query.filter(
            Data.id == id
        ).first()
        if data is None:
            data = Data(beizhu=beizhu, name=name, content=content)
            db.session.add(data)
            db.session.commit()
        else:
            data.beizhu = beizhu
            data.name = name
            data.content = content
            db.session.commit()
        return redirect(url_for("data.data_list"))